
package cn.varin.springai_ollama_chatinterfaceapi.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.stream.Stream;


@RestController
@Tag(name="客户端实例")

@RequestMapping("/client")
public class OllamaChatClientController {

	private static final String DEFAULT_PROMPT = "你好，介绍下你自己！请用中文回答。";

	private final ChatClient ollamaiChatClient;

	public OllamaChatClientController(ChatModel chatModel) {

		// 构造时，可以设置 ChatClient 的参数
		this.ollamaiChatClient = ChatClient.builder(chatModel)
				// 实现 Logger 的 Advisor
				.defaultAdvisors(
						new SimpleLoggerAdvisor()
				)
				// 设置 ChatClient 中 ChatModel 的 Options 参数
				.defaultOptions(
						OllamaOptions.builder()
								.topP(0.7)
								.model("deepseek-r1:1.5b")
								.build()
				)
				.build();
	}

	/**
	 * ChatClient 简单调用
	 */
	@Operation(summary = "无参数调用")

	@GetMapping("/simple/chat")
	public String simpleChat() {

		return ollamaiChatClient.prompt(DEFAULT_PROMPT).call().content();
	}

	/**
	 * ChatClient 流式调用
	 */
	@Operation(summary = "流式调用")

	@GetMapping("/stream/chat")
	public Flux<String> streamChat1(@RequestParam String message) {

		return ollamaiChatClient.prompt(message).stream().content();
	}

	@GetMapping("/stream")
	public SseEmitter streamChat2(@RequestParam String message) {
		SseEmitter emitter = new SseEmitter();

		Flux<String> content = ollamaiChatClient.prompt(message).stream().content();

		try {
			emitter.send(content);
			System.out.println(emitter.toString());

		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		return emitter;
	}

}